import os
import sys
import threading


class AccountIndexGenerator:
    def __init__(self):
        """
        初始化代理子账户编号生成器

        参数:
            file_path: 存储编号的文本文件路径
        """
        base_dir = os.path.dirname(os.path.realpath(sys.argv[0]))
        file_path = os.path.join(base_dir, 'configs/代理子账户编号.txt')
        self.file_path = file_path
        self.lock = threading.Lock()
        self._initialize_file()

    def _initialize_file(self):
        """初始化文件，如果文件不存在则创建并写入0"""
        with self.lock:
            if not os.path.exists(self.file_path):
                with open(self.file_path, 'w', encoding='utf-8') as f:
                    f.write('0')

    def get_next_account(self):
        """
        获取下一个代理子账户编号

        返回:
            下一个可用的代理子账户编号
        """
        with self.lock:
            # 读取当前编号
            with open(self.file_path, 'r', encoding='utf-8') as f:
                current_num = int(f.read().strip())

            # 计算下一个编号
            next_num = current_num + 1

            # 更新文件
            with open(self.file_path, 'w', encoding='utf-8') as f:
                f.write(str(next_num))

            return next_num

    def get_current_account(self):
        """
        获取当前代理子账户编号而不递增

        返回:
            当前的代理子账户编号
        """
        with self.lock:
            with open(self.file_path, 'r', encoding='utf-8') as f:
                return int(f.read().strip())